// pages/detail-search/index.js
import {
  getSearchHot,
  getSearchSuggest,
  getSearchResult
} from '../../../service/api_search.js'
import debounce from "../../../utils/debounce.js"

const debounceGetSearchSuggest = debounce(getSearchSuggest)

Page({
  data: {
    hots: [],
    suggestSongs: [],
    searchValue: "",
    resultSongs: []
  },
  onLoad: function (options) {
    this.getPageData()
  },
  onUnload: function () {

  },
  // 网络请求
  getPageData: function () {
    getSearchHot().then(res => {
      this.setData({
        hots: res.result.hots
      })
    })
  },
  // 事件处理
  handleSearchChange: function (event) {
    const searchValue = event.detail
    this.setData({
      searchValue
    })
    if (searchValue.length) {
      debounceGetSearchSuggest(searchValue).then(res => {
        // 获取建议的关键字歌曲
        this.setData({ 
          suggestSongs: res.result.allMatch
        })
      })
    } else {
      this.setData({ suggestSongs: [], resultSongs: [] })
      debounceGetSearchSuggest.cancel()
    }
  },
  handleSearchAction: function () {
    const searchValue = this.data.searchValue
    getSearchResult(searchValue).then(res => {
      this.setData({
        resultSongs: res.result.songs
      })
    })
  },
  handleKeywordItemClick: function (event) {
    const keyword = event.currentTarget.dataset.keyword
    this.setData({
      searchValue: keyword
    })
    this.handleSearchAction()
  }
})